

package com.njym.java.oss.controller;

import com.njym.java.oss.cloud.OSSFactory;
import com.njym.java.oss.constants.FileEntity;
import com.njym.java.oss.constants.FileUploadTool;
import com.njym.java.oss.constants.UploadService;
import com.njym.java.security.common.exception.BaseException;
import com.njym.java.security.common.msg.ObjectRestResponse;
import org.apache.commons.lang3.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * 文件上传
 * 
 * @author lj
 */
@RestController
@RequestMapping("/oss")
public class OssController{
	@Autowired
	private OSSFactory ossFactory;
	@Autowired
	private UploadService uploadService;
	/**
	 * 上传文件
	 */
	@RequestMapping("/upload")
	public ObjectRestResponse<String> upload(@RequestParam("file") MultipartFile file) throws Exception {
		if (file.isEmpty()) {
			throw new BaseException("上传文件不能为空");
		}
		//上传文件
		String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
		System.out.println("后缀：*********" +suffix);
		String url = ossFactory.build().uploadSuffix(file.getBytes(), suffix);
		return new ObjectRestResponse<>().data(url);
	}

	@PostMapping("/image")
	public ResponseEntity<String> uploadImage(@RequestParam("file") MultipartFile file){
		String url = uploadService.uploadImage(file);
		if(StringUtils.isBlank(url)){
			// url为空，证明上传失败
			return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
		}
		// 返回200，并且携带url路径
		return ResponseEntity.ok(url);
	}

	@RequestMapping("/video")
	public ObjectRestResponse<String> uploadVideo(@RequestParam(value = "file", required = false) MultipartFile multipartFile,
		HttpServletRequest request, ModelMap map) {
		String message = "";
		FileEntity entity = new FileEntity();
		FileUploadTool fileUploadTool = new FileUploadTool();
		try {
			entity = fileUploadTool.createFile(multipartFile, request);
			if (entity != null) {
				message = "上传成功";
				map.put("entity", entity);
				map.put("result", message);
			} else {
				message = "上传失败";
				map.put("result", message);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ObjectRestResponse<>().data(map);
	}
}
